<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON 转 TypeScript 对象工具</title>
    <style>
        /* 样式部分保持不变 */
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }

        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .editor-container {
            display: flex;
            gap: 20px;
        }

        @media (max-width: 768px) {
            .editor-container {
                flex-direction: column;
            }
        }

        .editor-box {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        textarea {
            width: 100%;
            height: 300px;
            font-family: Consolas, Monaco, 'Courier New', monospace;
            padding: 10px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
            resize: vertical;
        }

        label {
            font-weight: bold;
            margin-bottom: 5px;
        }

        button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #45a049;
        }

        .options {
            margin-bottom: 15px;
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 4px;
        }

        .option-group {
            margin-bottom: 10px;
        }

        .error {
            color: red;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <h1>JSON 转 TypeScript 对象工具</h1>

    <div class="container">
        <div class="options">
            <div class="option-group">
                <label>
                    <input type="checkbox" id="useInterface" checked>
                    使用 interface 而不是 type
                </label>
            </div>
            <div class="option-group">
                <label>
                    <input type="checkbox" id="useExport" checked>
                    添加 export 关键字
                </label>
            </div>
            <div class="option-group">
                <label>
                    <input type="checkbox" id="useSemicolon" checked>
                    使用分号
                </label>
            </div>
            <div class="option-group">
                <label>
                    <input type="checkbox" id="useTabs" checked>
                    使用制表符缩进
                </label>
            </div>
            <div class="option-group">
                <label>
                    根类型名称:
                    <input type="text" id="rootTypeName" value="RootObject">
                </label>
            </div>
            <div class="option-group">
                <label>
                    <input type="checkbox" id="extractNested" checked>
                    提取嵌套对象为独立类型
                </label>
            </div>
            <div class="option-group">
                <label>
                    命名空间:
                    <input type="text" id="namespace" placeholder="(可选)输入命名空间名称">
                </label>
            </div>
        </div>

        <div class="editor-container">
            <div class="editor-box">
                <label for="jsonInput">JSON 输入:</label>
                <textarea id="jsonInput" placeholder="在此粘贴 JSON 数据..."></textarea>
            </div>
            <div class="editor-box">
                <label for="tsOutput">TypeScript 输出:</label>
                <textarea id="tsOutput" readonly placeholder="转换后的 TypeScript 类型将显示在这里..."></textarea>
            </div>
        </div>

        <button id="convertBtn">转换为 TypeScript</button>
        <button id="copyBtn">复制结果</button>
        <button id="clearBtn">清空</button>

        <div id="errorMsg" class="error"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const jsonInput = document.getElementById('jsonInput');
            const tsOutput = document.getElementById('tsOutput');
            const convertBtn = document.getElementById('convertBtn');
            const copyBtn = document.getElementById('copyBtn');
            const clearBtn = document.getElementById('clearBtn');
            const errorMsg = document.getElementById('errorMsg');

            const useInterface = document.getElementById('useInterface');
            const useExport = document.getElementById('useExport');
            const useSemicolon = document.getElementById('useSemicolon');
            const useTabs = document.getElementById('useTabs');
            const rootTypeName = document.getElementById('rootTypeName');
            const extractNested = document.getElementById('extractNested');
            const namespaceInput = document.getElementById('namespace');

            convertBtn.addEventListener('click', convertJsonToTs);
            copyBtn.addEventListener('click', copyToClipboard);
            clearBtn.addEventListener('click', clearAll);

            function convertJsonToTs() {
                errorMsg.textContent = '';
                
                try {
                    const jsonStr = jsonInput.value.trim();
                    if (!jsonStr) {
                        throw new Error('请输入 JSON 数据');
                    }
                    
                    const jsonObj = JSON.parse(jsonStr);
                    const options = {
                        useInterface: useInterface.checked,
                        useExport: true, // 强制设置为true，忽略复选框状态
                        useSemicolon: useSemicolon.checked,
                        useTabs: useTabs.checked,
                        rootTypeName: rootTypeName.value.trim() || 'RootObject',
                        extractNested: extractNested.checked,
                        namespace: namespaceInput.value.trim(),
                        generatedTypes: new Map(),
                        typeNames: new Set()
                    };
                    
                    const tsCode = generateTypeScript(jsonObj, options);
                    tsOutput.value = tsCode;
                } catch (err) {
                    errorMsg.textContent = `错误: ${err.message}`;
                    console.error(err);
                }
            }

            function generateTypeScript(obj, options, indent = 0, parentKey = '') {
           const {
                    useInterface,
                    useExport, // 现在总是true
                    useSemicolon,
                    useTabs,
                    rootTypeName,
                    extractNested,
                    namespace,
                    generatedTypes,
                    typeNames
                } = options;

                const indentStr = useTabs ? '\t' : '    ';
                const currentIndent = indentStr.repeat(indent);
                const nextIndent = indentStr.repeat(indent + 1);
                const semicolon = useSemicolon ? ';' : '';

                let result = '';

                // 处理命名空间
                let namespaceStart = '';
                let namespaceEnd = '';
                if (namespace && indent === 0) {
                    const exportKeyword = useExport ? 'export ' : '';
                    namespaceStart = `${exportKeyword}namespace ${namespace} {\n\n`;
                    namespaceEnd = `\n}`;
                }

                if (indent === 0) {
                    // Root level
                  const keyword = useInterface ? 'interface' : 'type';
                    const exportKeyword = 'export '; // 总是添加export
                    result += namespaceStart;
                    result += `${exportKeyword}${keyword} ${rootTypeName} {\n`;

                    for (const [key, value] of Object.entries(obj)) {
                        const typeInfo = getType(value, options, indent + 1, key);
                        result += `${nextIndent}${key}: ${typeInfo.type}${semicolon}\n`;
                    }

                    result += `${currentIndent}}${semicolon}`;

                    // 添加生成的嵌套类型
                if (extractNested && generatedTypes.size > 0) {
                        result += '\n\n';
                        for (const [typeName, typeDef] of generatedTypes) {
                            const exportKeyword = 'export '; // 总是添加export
                            const keyword = useInterface ? 'interface' : 'type';
                            result += `${exportKeyword}${keyword} ${typeName} ${typeDef}\n\n`;
                        }
                    }
                    
                    result += namespaceEnd;
                } else {
                    if (Array.isArray(obj)) {
                        if (obj.length === 0) {
                            return { type: 'any[]' };
                        }

                        // 对于数组，我们只关心第一个元素的类型
                        const firstItem = obj[0];
                        if (typeof firstItem !== 'object' || firstItem === null) {
                            return { type: `${typeof firstItem}[]` };
                        }

                        // 处理对象数组
                        const typeInfo = getType(firstItem, options, indent, parentKey);
                        return { type: `${typeInfo.type}[]` };
                    } else if (typeof obj === 'object' && obj !== null) {
                        if (extractNested) {
                            // 尝试找到已有匹配的类型定义
                            const existingType = findExistingType(generatedTypes, obj);
                            if (existingType) {
                                return { type: existingType };
                            }

                            // 生成新的类型名称
                            let typeName = generateTypeName(parentKey, typeNames);

                            // 生成嵌套类型定义
                            let tempResult = '{\n';

                            for (const [key, value] of Object.entries(obj)) {
                                const typeInfo = getType(value, options, indent + 1, key);
                                tempResult += `${nextIndent}${key}: ${typeInfo.type}${semicolon}\n`;
                            }

                            tempResult += `${currentIndent}}`;

                            // 保存生成的类型
                            generatedTypes.set(typeName, tempResult);
                            typeNames.add(typeName);

                            return { type: typeName };
                        } else {
                            // 不提取嵌套对象，内联定义
                            let tempResult = '{\n';

                            for (const [key, value] of Object.entries(obj)) {
                                const typeInfo = getType(value, options, indent + 1, key);
                                tempResult += `${nextIndent}${key}: ${typeInfo.type}${semicolon}\n`;
                            }

                            tempResult += `${currentIndent}}`;
                            return { type: tempResult };
                        }
                    } else {
                        return { type: typeof obj };
                    }
                }

                return result;
            }

            // 生成唯一的类型名称
            function generateTypeName(baseName, typeNames) {
                baseName = baseName.charAt(0).toUpperCase() + baseName.slice(1);
                if (!typeNames.has(baseName)) {
                    return baseName;
                }

                let counter = 2;
                while (typeNames.has(`${baseName}${counter}`)) {
                    counter++;
                }
                return `${baseName}${counter}`;
            }

            // 查找是否已存在相同结构的类型
            function findExistingType(generatedTypes, obj) {
                const objString = JSON.stringify(normalizeObject(obj));
                for (const [typeName, typeDef] of generatedTypes) {
                    const typeObjString = typeDef.replace(/\s+/g, '');
                    if (typeObjString === `{${objString.replace(/\s+/g, '')}}`) {
                        return typeName;
                    }
                }
                return null;
            }

            // 规范化对象，确保属性顺序一致
            function normalizeObject(obj) {
                if (Array.isArray(obj)) {
                    return obj.map(normalizeObject);
                } else if (typeof obj === 'object' && obj !== null) {
                    const sortedObj = {};
                    Object.keys(obj).sort().forEach(key => {
                        sortedObj[key] = normalizeObject(obj[key]);
                    });
                    return sortedObj;
                }
                return obj;
            }

            function getType(value, options, indent, parentKey) {
                if (value === null) {
                    return { type: 'null' };
                }

                switch (typeof value) {
                    case 'string':
                        // Check if string is a date
                        if (/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/.test(value)) {
                            return { type: 'Date' };
                        }
                        return { type: 'string' };
                    case 'number':
                        return { type: 'number' };
                    case 'boolean':
                        return { type: 'boolean' };
                    case 'object':
                        if (Array.isArray(value)) {
                            return generateTypeScript(value, options, indent, parentKey);
                        } else {
                            return generateTypeScript(value, options, indent, parentKey);
                        }
                    default:
                        return { type: 'any' };
                }
            }

            function copyToClipboard() {
                if (!tsOutput.value) {
                    errorMsg.textContent = '没有内容可复制';
                    return;
                }

                tsOutput.select();
                tsOutput.setSelectionRange(0, 99999);
                document.execCommand('copy');

                // Show feedback
                const originalText = copyBtn.textContent;
                copyBtn.textContent = '已复制!';
                setTimeout(() => {
                    copyBtn.textContent = originalText;
                }, 2000);
            }

            function clearAll() {
                jsonInput.value = '';
                tsOutput.value = '';
                errorMsg.textContent = '';
            }
        });
    </script>
</body>

</html>